package com.handu.luna.boss.controller;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Date;
import java.util.Random;

import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.Mall;
import com.handu.luna.core.domain.article.ArticleList;
import com.handu.luna.core.domain.search.ArticleSearch;
import com.handu.luna.core.domain.support.FileUploadSupport;
import com.handu.luna.core.domain.support.FileUploadSupport.ImageType;

@Controller
@RequestMapping("/article/list/*")
public class ArticleListController extends BaseController{
	
	//点击搜索按钮
	@RequestMapping(value ="index",method = RequestMethod.POST)  //size = DEFAULT_PAGE_SIZE
	public BossModel index(ArticleSearch articleSearch,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort="id",direction= Direction.DESC) Pageable pageable)throws UnsupportedEncodingException{
		Mall mall=new Mall();
    	mall.articleInit();       
		    return createModel("/article/list/index")
				.add("categories", mall.getAllArticleCategories())
				.add("articleSearch",articleSearch)
				.add("articlePage",new ArticleList().findAll(articleSearch,pageable))
				.add("viewState", Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(articleSearch).toString().getBytes("UTF-8")));
				//.add("viewState", "");getUrlDecoder
		  
	}
	
	//点击文章分类，显示相应的文章列表

	@RequestMapping(value ="index/{id}",method = RequestMethod.GET)
	public BossModel index(@PathVariable long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort="id",direction= Direction.DESC) Pageable pageable)throws UnsupportedEncodingException{
		Mall mall=new Mall();
    	mall.articleInit(); 
    	ArticleSearch articleSearch = new ArticleSearch();
    	articleSearch.setArticleCategoryId(id+"");
    	if(id!=0){
    		return createModel("/article/list/index")
    				.add("categories", mall.getAllArticleCategories())
    				.add("articleSearch",articleSearch)
    				.add("articlePage",context.getArticleListRepository().findAll(new ArticleList().selectCondition(articleSearch),pageable))
    				.add("viewState", Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(articleSearch).toString().getBytes("UTF-8")));
    	}else{
		    return createModel("/article/list/index")
				.add("categories", mall.getAllArticleCategories())
				.add("articleSearch",articleSearch)
				.add("articlePage",new ArticleList().findAll(pageable))
				.add("viewState", Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(articleSearch).toString().getBytes("UTF-8")));
    	}
		
	}
	
	//搜索 和列表 分页
	
	@RequestMapping(value = "index")   //createdDate
	public BossModel index(String viewState,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE,sort="id",direction= Direction.DESC) Pageable pageable)throws UnsupportedEncodingException {
		ArticleSearch articleSearch;
		if(viewState != null && !viewState.trim().equals("")){ 
		   //解析传递过来的查询json字符串
			articleSearch = (ArticleSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState),"UTF-8")), ArticleSearch.class);
		    Mall mall=new Mall();
    	    mall.articleInit();  
        	
		    return createModel("/article/list/index")
				.add("articlePage",new ArticleList().findAll(articleSearch, pageable))
				.add("categories", mall.getAllArticleCategories())
				.add("articleSearch",articleSearch)
				.add("viewState", viewState);
	   }else{
		   articleSearch = new ArticleSearch();
		   Mall mall=new Mall();
   	       mall.articleInit();  
		    return createModel("/article/list/index")
				.add("articlePage",new ArticleList().findAll(articleSearch, pageable))
				.add("categories",  mall.getAllArticleCategories())
				.add("articleSearch",new ArticleSearch())
				.add("viewState", "");
	   }
	}
	
	@RequestMapping(value = "add")
	public BossModel add(){
        Mall mall=new Mall();
    	mall.articleInit();          
		ArticleList artList = new ArticleList();
		artList.setDisplayed(true);
		artList.setArticleType(false);
		artList.setSortOrder(100);
		return createModel("article/list/save").add("articleList", artList).add("cateParents", mall.getAllArticleCategories());   //mall.getAllArticleCategories()
	}
	
	@RequestMapping(value = "edit/{id}")
	public BossModel edit(@PathVariable long id) {
		Mall mall=new Mall();
    	mall.articleInit();     	
		return createModel("article/list/save").add("articleList",context.getArticleListRepository().findOne(id)).add("cateParents",mall.getAllArticleCategories());
	}
	
	@RequestMapping(value = "delete")
	public BossModel delete(
			String viewState,
			String chestr,
			long id,
			@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE,sort="id",direction= Direction.DESC) Pageable pageable) {
		
		if (chestr != null) {
			String[] array = chestr.split(",");
			for (int i = 0; i < array.length; i++) {
				context.getArticleListRepository().delete(Long.valueOf(array[i]));
			}
		} else {
			context.getArticleListRepository().delete(id);
		}
		
		Mall mall=new Mall();
    	mall.articleInit(); 
		return createModel("article/list/article_table").add("articlePage",
				new ArticleList().findAll(pageable)).add(
				"viewState", viewState).add("categories", mall.getAllArticleCategories());
	}
	
	//单个的显示，隐藏
	@RequestMapping(value="updateStateSingle", method = RequestMethod.POST)
	public BossModel update(long id,Boolean text,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE,sort="id",direction= Direction.DESC) Pageable pageable){
		if(text==false){
			ArticleList ArticleList = context.getArticleListRepository().findOne(id);
			ArticleList.setDisplayed(true);
			context.getArticleListRepository().updateDisplayedTrue(ArticleList.isDisplayed(), id);
		}else{
	       ArticleList ArticleList = context.getArticleListRepository().findOne(id);
	       ArticleList.setDisplayed(false);
	      context.getArticleListRepository().updateDisplayedTrue(ArticleList.isDisplayed(), id);
	    }
		return createModel("article/list/article_table").add("articlePage",new ArticleList().findAll(pageable));
	}
	  
	  
	  //批量显示 ，隐藏 , 转移分类
	@RequestMapping(value = "updateState", method = RequestMethod.POST)
	public BossModel update(
			String viewState,
			String chestr,
			String status,
			String val,
			long id,
			@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE,sort="id",direction= Direction.DESC) Pageable pageable) {

		if ("up".equals(status) && chestr != null) {// 显示
			String[] array = chestr.split(",");
			for (int i = 0; i < array.length; i++) {	
				ArticleList list = context.getArticleListRepository().findOne(Long.valueOf(array[i]));
				list.setDisplayed(true);
				context.getArticleListRepository().updateDisplayedTrue(list.isDisplayed(), Long.valueOf(array[i]));
				
			}
		} else if ("down".equals(status) && chestr != null) {// 隐藏
			String[] array = chestr.split(",");
			for (int i = 0; i < array.length; i++) {	
				ArticleList articleList  = context.getArticleListRepository().findOne(Long.valueOf(array[i]));
				articleList.setDisplayed(false);
				context.getArticleListRepository().updateDisplayedTrue(articleList.isDisplayed(), Long.valueOf(array[i]));
			}
		} else if ("turn".equals(status) && chestr != null) {// 转移分类
			String[] array = chestr.split(",");
			for (int i = 0; i < array.length; i++) {
					
				ArticleList list  = context.getArticleListRepository().findOne(Long.valueOf(array[i]));
				list.setCatId(Long.valueOf(val));
				context.getArticleListRepository().updateCategoryId(list.getCatId(), Long.valueOf(array[i]));
			}
		}
		
		Mall mall=new Mall();
    	mall.articleInit();
		return createModel("article/list/article_table").add("articlePage",
				new ArticleList().findAll(pageable)).add(
				"viewState", viewState).add("categories", mall.getAllArticleCategories());		
	}
	
	
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	@InitBinder(value={"title","catId","articleType","displayed","sortOrder","keywords","description","content","link","fileUrl"})
	public BossModel save(@Valid final ArticleList articleList,final BindingResult bindingResult,RedirectAttributes redirectAttributes,
			@RequestParam("uploadfile") MultipartFile file){
		String message = "";
		Mall mall=new Mall();
    	mall.articleInit(); 

		   
		if(bindingResult.hasErrors()){
			return createModel("article/list/save").add("cateParents", mall.getAllArticleCategories());
		}
	
		int num = 0;
		int nullFileUrl = 0;
		int writePath = 0;
		if (!file.isEmpty() && "".equals(articleList.getFileUrl())) {
			String fileurl = saveFile(file);
			if(fileurl==null){
				nullFileUrl = 1;
			}else{
		    	articleList.setFileUrl(fileurl);
			}
			
		}else if(file.isEmpty() && !("".equals(articleList.getFileUrl()))){
			String url = articleList.getFileUrl();   //gif|jpg|jpeg|png
			if((url.startsWith("http://", 0) || url.startsWith("/", 0) ) && (url.endsWith(".jpg") || url.endsWith(".gif") || url.endsWith(".jpeg") || url.endsWith(".png") )){
				articleList.setFileUrl(url);
			}else{
				writePath = 1;
			}
		}else if(!file.isEmpty() && articleList.getFileUrl()!=null){
			num=1;	
		}	
		
   	//当添加文章的时候，先判断  所属分类  是否存在
		Long CategoryNumCheckById = 0l;
		if(articleList.getCatId()!=0){
			CategoryNumCheckById = context.getArticleCategoryRepository().count("id",articleList.getCatId());
		}
	 

	  //判断传过来的 文章标题  是否全部为空格
	 // boolean flag = false;
	  String title = articleList.getTitle().trim();
	/*  int i = articleList.getTitle().trim().indexOf(" ");
	  if(i==-1)
	  {
		 flag = true;
	  }else{
	     flag = false;
	  }*/

		
		if(CategoryNumCheckById==0 && articleList.getCatId()!=0){
			  message = "所添加文章的分类已被删除";
		}
		else if(num==1){
			 message = "上传文件地址发生了冲突，请选择其一";
		}else if((null==articleList.getId() || articleList.getId()==0) && (!title.isEmpty()) && articleList.getSortOrder()!=0 && nullFileUrl!=1 && writePath!=1)
		{
			context.getArticleListRepository().save(articleList);
			message = "添加" + articleList.getTitle() +"成功";
		}else if(title.isEmpty()){
			message = "文章标题不能为空！";
			
		}else if(nullFileUrl==1){
			message = "所上传文件类型不是图片";
			
		}else if(writePath==1){
			message = "所填写的图片路径不合格！";
			
		}else{
			context.getArticleListRepository().save(articleList);
			message = "修改" + articleList.getTitle() +"成功";
		}
		
		//context.getArticleListRepository().save(articleList);
		redirectAttributes.addFlashAttribute("message",message);
		return createModel("redirect:index");		
		
	}
	
	
	/***
	 * 保存文件
	 * @param file
	 * @return
	 */
	private @ResponseBody() String saveFile(MultipartFile file) {

        if (!file.isEmpty()) {
            try {
            	/*命名规则*/
            	String pic_type = file.getContentType();
            	String fileName;
            	Random random = new Random();
    			int x = random.nextInt(899999);
    			int randomValue = x+100000;

            	String file_ture_name = new Date().getTime()+randomValue+"_s";
            	if(pic_type.equals("image/jpg")){
            		fileName =   file_ture_name.concat(".jpg");  
            	} else if (pic_type.equals("image/png")){
            		fileName = file_ture_name.concat(".png");
            	} else if(pic_type.equals("image/jpeg")){
            		fileName =  file_ture_name.concat(".jpeg");
            	} else if(pic_type.equals("image/gif")){
            		fileName = file_ture_name.concat(".gif");
            	} else	{ 
            		return null; //"You failed to upload " + file.getName() + " because the file type is not pictures";
            	}
            	
            	String returnMessage = FileUploadSupport.upload(file.getInputStream(), fileName, ImageType.ARTICLES);
                return returnMessage;
            } catch (Exception e) {
                return "You failed to upload " + file.getName() + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + file.getName() + " because the file was empty.";
        }
	}
	
	

}
